#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#include "queue.h"

//初始化队列
void InitQueue(Queue *q)
{
    q->front = NULL;
    q->rear = NULL;
    q->items = 0;
}

//判断队列是否满
bool QueueIsFull(Queue *q)
{
    return q->items == MAX_QUEUE;
}

//判断队列空
bool QueueIsEmpty(Queue *q)
{
    return q->items == 0;
}

//统计个数
int QueueItems(Queue *q)
{
    return q->items;
}

//向队尾添加项目
bool QueueAdd(Queue *q, Item item)
{
    if(QueueIsFull(q)){
        return false;
    }

    Node *pnode = (Node *)calloc(1, sizeof(Node));
    pnode->item = item;

    if(QueueIsEmpty(q)){
        q->front = pnode;
    }else{
        q->rear->next = pnode;
    }

    q->rear = pnode;
    q->items++;

    return true;
}


//从队首删除项目
bool QueueDelete(Queue *q, Item *pitem)
{
    if(QueueIsEmpty(q)){
        return false;
    }

    *pitem = q->front->item;
    Node *ptemp = q->front;
    q->front = q->front->next;
    
    free(ptemp);
    q->items--;

    if(QueueIsEmpty(q)){
        q->rear = NULL;
    }

    return true;

}

//清空队列
void QueueEmpty(Queue *q)
{
    Item temp;
    while(!QueueIsEmpty(q)){
        QueueDelete(q, &temp);
    }
}